/**
 * 文件名：ControllerSupport.java
 *
 * 版本信息：
 * 日期：Sep 5, 2014
 * Copyright © 2014 , All Rights Reserved
 *
 */
package com.support.web;

import com.bdyt.util.WebUtils;
import com.support.jdbc.Page;
import com.support.util.StringUtils;

import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名称：ControllerSupport 类描述：Cotroller基类 创建人：Fangyuan Chen 创建时间：Sep 5, 2014
 * 10:29:04 AM 修改人： 修改时间： 修改备注：
 * 
 * @version 1.0
 */
public class ControllerSupport
{

	protected static final Integer PAGE_SIZE = 20;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	protected ServletContext context;
	private static ApplicationContext applicationContext = null;

	/**
	 * 设置Request和Response
	 * 
	 * @param arg0
	 * @param arg1
	 */
	@ModelAttribute
	public void setRequestAndResponse(HttpServletRequest arg0, HttpServletResponse arg1)
	{
		this.request = arg0;
		this.response = arg1;
		this.session = request.getSession();
		this.context = this.context == null ? ContextLoader.getCurrentWebApplicationContext().getServletContext() : this.context;
	}

	/**
	 * 获取参数Map
	 * 
	 * @return
	 * @throws Exception
	 */
	protected Map<String, String> getParamsMap() throws Exception
	{
		Map<String, String> params = new HashMap<String, String>();
		if (request != null)
		{
			Enumeration<?> nameEnumeration = request.getParameterNames();
			while (nameEnumeration.hasMoreElements())
			{
				String paramName = String.valueOf(nameEnumeration.nextElement());
				String paramValue = request.getParameter(paramName);
				params.put(paramName.toUpperCase(), "".equals(paramValue) ? null : paramValue);
			}
		}
		// Account account = getCurrentUser();
		// params.put("currentUser", account.getAccountID());
		// if(account != null && account.getOrg() != null)
		// {
		// params.put("orgNo", account.getOrg().getOrgNo());
		// }
		// else
		// {
		// params.put("orgNo", "");
		// }
		// 校验接口调用时参数是否合法
		if (!checkParamsVerfiy(params))
		{
			throw new Exception("您没有调用该接口的权限或参数错误");
		}

		// 对参数值进行解码
		for (Map.Entry<String, String> en : params.entrySet())
		{
			params.put(en.getKey(), WebUtils.decode(en.getValue()));
		}
		return params;
	}

	protected Map<String, Object> getParamsObjectMap() throws Exception
	{
		Map<String, Object> params = new HashMap<String, Object>();
		if (request != null)
		{
			Enumeration<?> nameEnumeration = request.getParameterNames();
			while (nameEnumeration.hasMoreElements())
			{
				String paramName = String.valueOf(nameEnumeration.nextElement());
				String paramValue = request.getParameter(paramName);
				if ("true".equalsIgnoreCase(paramValue) || "false".equalsIgnoreCase(paramValue))
				{
					params.put(paramName, Boolean.parseBoolean(paramValue));
				}
				else
				{
					params.put(paramName, "".equals(paramValue) ? null : paramValue);
				}
				params.put(paramName.toUpperCase(), "".equals(paramValue) ? null : paramValue);
			}
		}
		// Account account = getCurrentUser();
		// params.put("currentUser", account.getAccountID());
		// if(account != null && account.getOrg() != null) {
		// params.put("orgNo", account.getOrg().getOrgNo());
		// }else{
		// params.put("orgNo", "");
		// }

		// 校验接口调用时参数是否合法
		/*
		 * if(!checkParamsVerfiy(params)) { throw new
		 * Exception("您没有调用该接口的权限或参数错误"); }
		 * 
		 * // 对参数值进行解码 for (Map.Entry<String, String> en : params.entrySet()) {
		 * params.put(en.getKey(), WebUtils.decode(en.getValue())); }
		 */
		return params;
	}

	/**
	 * 获取参数Map
	 * 
	 * @return
	 * @throws Exception
	 */
	protected Map<String, String> getParamsStringMap() throws Exception
	{
		Map<String, String> params = new HashMap<String, String>();
		if (request != null)
		{
			Enumeration<?> nameEnumeration = request.getParameterNames();
			while (nameEnumeration.hasMoreElements())
			{
				String paramName = String.valueOf(nameEnumeration.nextElement());
				String paramValue = request.getParameter(paramName);
				params.put(paramName.toUpperCase(), "".equals(paramValue) ? null : paramValue);
			}
		}
		// Account account = getCurrentUser();
		// params.put("currentUser", account.getAccountID());
		// params.put("orgNo", account.getOrg().getOrgNo());

		// 校验接口调用时参数是否合法
		if (!checkParamsVerfiy(params))
		{
			throw new Exception("您没有调用该接口的权限或参数错误");
		}

		// 对参数值进行解码
		for (Map.Entry<String, String> en : params.entrySet())
		{
			params.put(en.getKey(), WebUtils.decode(en.getValue()));
		}
		return params;
	}

	/**
	 * 分页接口调用该方法获取参数
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Page<?> getParamsPage() throws Exception
	{
		Page page = new Page();
		Map<String, String> params = getParamsMap();
		String size = params.get("PAGESIZE") == null ? "10" : String.valueOf(params.get("PAGESIZE"));
		String pageNo = params.get("CURRENTPAGEINDEX") == null ? "1" : String.valueOf(params.get("CURRENTPAGEINDEX"));

		size = StringUtils.isEmpty(size) ? "0" : size;
		pageNo = (StringUtils.isEmpty(pageNo) || "0".equals(pageNo)) ? "1" : pageNo;
		page.setPageSize(Integer.parseInt(size));
		page.setPageNo(Integer.parseInt(pageNo));
		page.setParams(params);

		return page;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Page<?> getParamsPage4JQGrid() throws Exception
	{
		Map<String, String> params = getParamsMap();

		Page page = new Page();
		String size = params.get("PAGESIZE") == null ? "0" : String.valueOf(params.get("PAGESIZE"));
		String pageNo = params.get("CURRENTPAGEINDEX") == null ? "1" : String.valueOf(params.get("CURRENTPAGEINDEX"));

		size = StringUtils.isEmpty(size) ? "0" : size;
		pageNo = (StringUtils.isEmpty(pageNo) || "0".equals(pageNo)) ? "1" : pageNo;

		page.setPageSize(Integer.parseInt(size));
		page.setPageNo(Integer.parseInt(pageNo));
		page.setParams(params);
		return page;
	}

	private boolean checkParamsVerfiy(Map<String, String> params)
	{
		return true;
		/*
		 * String appid = params.get("APPID"); String sign = params.get("SIGN");
		 * 
		 * if(StringUtils.isEmpty(appid) || StringUtils.isEmpty(sign)) { return
		 * false; }
		 * 
		 * // TODO 修改根据分配给客户端的key获取对应的公钥，接口调用者的公钥从缓存中获取 String public_key =
		 * "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVT+pLc1nkz9z803SOmF48bMFn0GYF4ng6nxj0ojUeu4KeNKkkw/nfureTtL77j9RpMjquJzzKdOZfHRvQyuAbaLoaSD1uU47npNiAL05bLYZEoZWvFOar9gNbIesea8MX0DeYncA2Tkr3kUo8K6XBrZ+TcV2Q8NEvm1T536LOGwIDAQAB"
		 * ;
		 * 
		 * return com.bdyt.util.Notify.getSignVeryfy2(params, public_key, sign,
		 * params.get("CHARTSET"));
		 */
	}

	/**
	 * 返回JSON对象
	 * 
	 * @param json
	 * @throws IOException
	 */
	public void returnJSONView(String json) throws IOException
	{
		HttpResponseHelper.response(response, json);
	}

	/**
	 * 返回JSON对象
	 * 
	 * @param outstring
	 * @throws IOException
	 */
	public void returnStrView(String outstring) throws IOException
	{
		HttpResponseHelper.responseScript(response, outstring);
	}

	public static ApplicationContext getContext()
	{
		if (applicationContext == null)
		{
			applicationContext = WebApplicationContextUtils.getWebApplicationContext(ContextLoader.getCurrentWebApplicationContext().getServletContext());
		}
		return applicationContext;
	}
}
